// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm.analysis;

import org.objectweb.asm.tree.analysis.Frame;
import org.objectweb.asm.tree.analysis.Value;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class FrameUtils {
  /**
   * Returns the value stored at the top of the stack.
   * 
   * @param frame a frame
   * @return a value at the top of the stack
   */
  public static Value top(Frame frame) {
    return top(frame, 0);
  }
  
  /**
   * Returns the value stored at given index counting from the top of the stack.
   * 
   * @param frame a frame
   * @param index stack index
   * @return a value at the top of the stack
   */
  public static Value top(Frame frame, int index) {
    int stackSize = frame.getStackSize();
    return frame.getStack(stackSize - 1 - index);
  }
  
  /**
   * Returns string representation of all local values in this frame.
   * 
   * @param frame the frame
   * @return the string
   */
  public static String localsString(Frame frame) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < frame.getLocals(); i++) {
      if (i != 0) stringBuilder.append("|");
      stringBuilder.append(frame.getLocal(i));
    }
    return stringBuilder.toString();
  }
}
